package cn.hchaojie.web.day04;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("loginFilter 初始化");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		// 登陆的界面不要判断登陆状态
		String uri = req.getRequestURI();
		// localhost/day04/login.html
		if (uri.contains("login.html") || uri.contains("login")) {
			chain.doFilter(request, response);	
			return;
		}
		
		// 如果session里面有用户名，说明登陆过，那么请求就直接放行，请求就转发到下一个过滤器或者servlet
		// 如果没有，那么我们直接返回登陆界面
		HttpSession session = ((HttpServletRequest) request).getSession();
		String user = (String) session.getAttribute("user");
		if (user == null) {	// 没有登陆
			((HttpServletResponse) response).sendRedirect("login.html");
		} else {
			// 如果登陆了，请求放行
			chain.doFilter(request, response);
		}
		
		System.out.println("loginFilter.doFilter...");
	}

	@Override
	public void destroy() {
		System.out.println("loginFilter.destroy...");
	}

}
